import React, {Component, useContext, useEffect, useReducer, useState} from 'react';
import axios from "axios";
import '../02-advanced/filmpage.css'

//创建Context对象
//供应商给客户提供服务
//useContext减少组件层级
const GlobalContext = React.createContext()

export default function App(){
    const [info, setInfo] = useState('')
    const [list, setList] = useState([])

    useEffect(()=>{
        axios.get(`test.json`).then(res => {
            setList(res.data.data.films)
        })
    },[])

    return(
        <GlobalContext.Provider className="Provider" value={{//可写:方法,对象
            call: '打电话',
            sms: '短信服务',
            info:info,
            changeInfo:(val)=>{
                setInfo(val)
            }
        }}>
            <div>
                {
                    list.map(item =>
                        <Filmitem key={item.filmId} {...item}></Filmitem>
                    )
                }

                <FilmDetail info={info}></FilmDetail>
            </div>
        </GlobalContext.Provider>
    )
}

//受控组件

function Filmitem(props) {
    let {name, poster, grade, synopsis} = props
    const value=useContext(GlobalContext)
    // return (
        // <GlobalContext.Consumer className="Consumer">
        //     {
        //         (value) => {
                    return (
                        <div className='filmitem' onClick={() => {
                            value.changeInfo(synopsis)
                        }}>
                            <img src={poster} alt={name}/>
                            <h4>{name}</h4>
                            <div>观众评分：{grade}</div>
                        </div>
                    )
        //         }
        //     }
        // </GlobalContext.Consumer>
    // )
}

function FilmDetail() {
    const value=useContext(GlobalContext)
    // return (
    //     <GlobalContext.Consumer className="Consumer">
    //         {
    //             (value) => {
                    return (
                        <div className='filmiDetail'>
                            {value.info}
                        </div>
                    )
    //             }
    //         }
    //     </GlobalContext.Consumer>
    // )
}




